<!DOCTYPE html>
<html>

<head>
    <script src="./js/fabric.js"></script>
</head>

<body>
    <button id="toggleMode">Switch to Eraser</button>
    <canvas id="c" width="800" height="600" style="border:1px solid black;"></canvas>
    <canvas id="c2" width="800" height="600" style="border:1px solid black;"></canvas>
    <script>
        const canvas = new fabric.Canvas('c');
        const canvas2 = document.getElementById('c2');
        const ctx2 = canvas2.getContext('2d');

        // 使用PencilBrush
        const pencilBrush = new fabric.PencilBrush(canvas);
        canvas.freeDrawingBrush = pencilBrush;
        canvas.isDrawingMode = true;

        pencilBrush.limitedToCanvasSize = true; // 禁止画笔超出画布
        // pencilBrush.color = this.brushColor;
        pencilBrush.width = 20;


        // 初始化为绘制模式
        let isErasing = false;

        // 切换按钮
        const toggleButton = document.getElementById('toggleMode');
        toggleButton.addEventListener('click', function () {
            isErasing = !isErasing;
            if (isErasing) {
                canvas.freeDrawingBrush = new fabric.EraserBrush(canvas);
                toggleButton.textContent = 'Switch to Pencil';
            } else {
                canvas.freeDrawingBrush = pencilBrush;
                toggleButton.textContent = 'Switch to Eraser';
            }
        });

        // 监听绘制过程中的mouse:move事件来实时同步绘制内容
        canvas.on('mouse:move', function () {
            if (canvas.isDrawingMode) {
                // 将Fabric.js canvas的内容绘制到原生canvas上
                ctx2.clearRect(0, 0, canvas2.width, canvas2.height); // 清除原有内容
                ctx2.drawImage(canvas.lowerCanvasEl, 0, 0);
                ctx2.drawImage(canvas.upperCanvasEl, 0, 0);
            }
        });

        // 你还可以监听'draw:start'和'draw:updated'事件
        canvas.on('mouse:down', function (event) {
            if (canvas.isDrawingMode) {
                console.log('Drawing started');
            }
        });

        canvas.on('mouse:up', function (event) {
            if (canvas.isDrawingMode) {
                console.log('Drawing ended');
            }
        });

    </script>
</body>

</html>